var valleyInfos = new Array();

$(document).ready(
	function(){ 
		$('#consoleDlg')[0].style.display = "none";
		
		$("#gridTable").jqGrid({   
            url:getContextPath()+"/site/site/getAllSites.do",   
            datatype: "json",// "local",
            height: 350, //"auto"   
            colNames:['编号','站点名称','监测类别','区域','流域', '水系', '断面','评测标准'],
			colModel:[
				{name:'id', index:'id', width:70, align:"left"},
				{name:'name', index:'name', width:150, align:"left"},
				{name:'monitorType.name', index:'monitorType.name', width:100, align:"left"},
				{name:'area.province', index:'area.province', width:70, align:"left"},
		   		{name:'valley.name', index:'valley.name', width:100, align:"left"},
		   		{name:'valley.waterSystem', index:'valley.waterSystem', width:100, align:"left"},
		   		{name:'valley.alongSide', index:'valley.alongSide', width:100, align:"left"},
		   		{name:'qualityName', index:'qualityName', width:100, align:"left"}
			],
            sortname:'id',   
            // sortorder:'asc',
            viewrecords:true, 
            pgtext : "页 {0} 共 {1}页",
            recordtext:'记录 {0} - {1} 总记录数 {2}',  
            emptyrecords : "无数据",
            loadtext : "获取数据中...",
            rowNum: 15,//10,   
            loadonce: true,
            //rowList:[15, 30],   
            jsonReader: { 
				repeatitems:false,   	 // 设置成false，在后台设置值的时候，可以乱序。且并非每个值都得设
				root: "rows",               // 数据行（默认为：rows）   
				total: "total",        // 总记录数   
				page: "page",            // 当前页   
				records: "records"
                //root:"dataRows",        // 数据行（默认为：rows）
                //page: "pages",    // 当前页
                //total: "totals",  // 总页数
                //records: "records",  // 总记录数
                //repeatitems : false    
            }, 
            //prmNames : {
				//search : "search",
				//rows:"pageModel.rows",
				//page:"pageModel.page",
				// sort:"page.orderBy",
				// order:"page.order"
			//}, 
            pager:"#gridPager",  
            caption: "站点信息 "
		});  
		$("#gridTable").jqGrid('navGrid','#gridPager',{edit:false,add:false,del:false});
		
		// 配置对话框
		$("#consoleDlg").dialog( {
			autoOpen : false,
			modal : true, // 设置对话框为模态（modal）对话框
			resizable : true,
			width : 900,
			buttons : { // 为对话框添加按钮
				"取消" : function() {
					$("#consoleDlg").dialog("close")
				},
				"添加" : addInfo,
				"保存" : updateInfo,
				"删除" : deleteInfo
			}
		});  
		
		//初始化对话框中的MonitorType下拉框
		$.ajax({
			type: "POST",
			url : getContextPath()+"/base/monitorType/getAllMonitorTypesObj.do", 
			data : {},
			dataType : "json",
			async : false,
			cache: false,
			error : function(textStatus, errorThrown) {
				alert("系统ajax交互错误: " + textStatus);
			},
			success : function(data, textStatus) {
				if (data != null) {
					var roleSelect = $("#consoleDlg").find("#monitorType");
					for (var i=0; i<data.length; i++) {
						//ie8不支持
						//roleSelect.append(new Option(data[i].name, data[i].id));
						roleSelect.append('<option value="'+data[i].id+'">'+data[i].name+'</option>');
					}
				}
			}
		});
		
		//初始化对话框中的area下拉框
		$.ajax({
			type: "POST",
			url : getContextPath()+"/base/area/getAllAreasObj.do", 
			data : {},
			dataType : "json",
			async : false,
			cache: false,
			error : function(textStatus, errorThrown) {
				alert("系统ajax交互错误: " + textStatus);
			},
			success : function(data, textStatus) {
				if (data != null) {
					var areaSelect = $("#consoleDlg").find("#area");
					for (var i=0; i<data.length; i++) {
						//ie8不支持
						//areaSelect.append(new Option(data[i].areaID+":"+data[i].province+"/"+data[i].city+"/"+data[i].district, data[i].id));
						areaSelect.append('<option value="'+data[i].id+'">'+data[i].areaID+":"+data[i].province+"/"+data[i].city+"/"+data[i].district+'</option>');
					}
				}
			}
		});
		
		var valleynameSelect = $("#consoleDlg").find("#valleyname");
		var waterSystemSelect = $("#consoleDlg").find("#waterSystem");
		var alongSideSelect = $("#consoleDlg").find("#alongSide");
		
		//初始化对话框中的valleyname下拉框
		$.ajax({
			type: "POST",
			url : getContextPath()+"/base/valley/getAllValleysObj.do", 
			data : {},
			dataType : "json",
			async : false,
			cache: false,
			error : function(textStatus, errorThrown) {
				alert("系统ajax交互错误: " + textStatus);
			},
			success : function(data, textStatus) {
				if (data != null) {
					valleyInfos = data;
				}
			}
		});
		//将valleyInfos中的name放置入valleyname下拉框
		valleynameSelect.empty();
		//ie8不支持
		//valleynameSelect.append(new Option("--请选择--","no"));
		valleynameSelect.append('<option value="'+"no"+'">'+"--请选择--"+'</option>');
		for (var i=0; i<valleyInfos.length; i++) {
			if ($("#valleyname option[value="+valleyInfos[i].name+"]").length==0) {
				//ie8不支持
				//valleynameSelect.append(new Option(valleyInfos[i].name, valleyInfos[i].name));
				valleynameSelect.append('<option value="'+valleyInfos[i].name+'">'+valleyInfos[i].name+'</option>');
			}
		}
		
		//初始化valleyname的二级联动,根据valleyname下拉框的取值val重置waterSystem下拉框内容
		valleynameSelect.change(function() {
			var curVal = valleynameSelect.val();
			waterSystemSelect.empty();
			//ie8不支持
			//waterSystemSelect.append(new Option("--请选择--","no"));
			waterSystemSelect.append('<option value="'+"no"+'">'+"--请选择--"+'</option>');
			alongSideSelect.empty();
			//ie8不支持
			//alongSideSelect.append(new Option("--请选择--","no"));
			alongSideSelect.append('<option value="'+"no"+'">'+"--请选择--"+'</option>');
			if (curVal != "no") {
				for (var i=0; i<valleyInfos.length; i++) {
					if ($("#waterSystem option[value="+valleyInfos[i].waterSystem+"]").length==0 && valleyInfos[i].name==curVal) {
						//ie8不支持
						//waterSystemSelect.append(new Option(valleyInfos[i].waterSystem, valleyInfos[i].waterSystem));
						waterSystemSelect.append('<option value="'+valleyInfos[i].waterSystem+'">'+valleyInfos[i].waterSystem+'</option>');
					}
				}
			}
		});
		
		//初始化valleyname与waterSystem的三级联动,根据valleyname下拉框和waterSystem下拉框的取值val重置alongSide下拉框内容
		waterSystemSelect.change(function() {
			var curVal1 = valleynameSelect.val();
			var curVal2 = waterSystemSelect.val();
			alongSideSelect.empty();
			//ie8不支持
			//alongSideSelect.append(new Option("--请选择--","no"));
			alongSideSelect.append('<option value="'+"no"+'">'+"--请选择--"+'</option>');
			if (curVal2 != "no") {
				for (var i=0; i<valleyInfos.length; i++) {
					if ($("#alongSide option[value="+valleyInfos[i].alongSide+"]").length==0 && valleyInfos[i].name==curVal1 && valleyInfos[i].waterSystem==curVal2) {
						//ie8不支持
						//alongSideSelect.append(new Option(valleyInfos[i].alongSide, valleyInfos[i].alongSide));
						alongSideSelect.append('<option value="'+valleyInfos[i].alongSide+'">'+valleyInfos[i].alongSide+'</option>');
					}
				}
			}
		});
	}
)

		// getContextPath
		function getContextPath() {
    		var pathName = document.location.pathname;
    		var index = pathName.substr(1).indexOf("/");
    		var result = pathName.substr(0,index+1);
    		return result;
		};

		var openDialog4Adding = function() {  
			var consoleDlg = $("#consoleDlg");  
			var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");  
			consoleDlg.find("input").removeAttr("disabled").val(""); 
			consoleDlg.find("select").removeAttr("disabled").val("no");
			//特殊情况 gpsFixed
			consoleDlg.find("#gpsFixed").val("F");
			consoleDlg.find("textarea").val("").removeAttr("disabled");
			dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
			dialogButtonPanel.find("button:contains('添加')").show();  
			consoleDlg.dialog("option", "title", "添加站点信息 ").dialog("open");  
		};  
		
		var openDialog4Updating = function() {
			var consoleDlg = $("#consoleDlg");  
	        var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");    
	        consoleDlg.find("input").val("").removeAttr("disabled"); 
	        consoleDlg.find("select").removeAttr("disabled");
	        consoleDlg.find("textarea").val("").removeAttr("disabled"); 
	        consoleDlg.find("#id").attr("disabled", true);
	        dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
	        dialogButtonPanel.find("button:contains('保存')").show();  
	        consoleDlg.dialog("option", "title", "修改站点信息");  
	          
	        loadSelectedRowData();  
		};
		
		var openDialog4Deleting = function() {
			var consoleDlg = $("#consoleDlg");  
	        var dialogButtonPanel = consoleDlg.siblings(".ui-dialog-buttonpane");         
	        consoleDlg.find("input").attr("disabled", true); 
	        consoleDlg.find("select").attr("disabled", true); 
	        consoleDlg.find("textarea").attr("disabled", true); 
	        dialogButtonPanel.find("button:not(:contains('取消'))").hide();  
	        dialogButtonPanel.find("button:contains('删除')").show();  
	        consoleDlg.dialog("option", "title", "删除站点信息");  
	          
	        loadSelectedRowData();  
		};
		
		var loadSelectedRowData = function() {
			var selectedRowId = $("#gridTable").jqGrid("getGridParam", "selrow");
	    	//alert("selectRowID:"+selectedRowId);
	    	if (!selectedRowId) {
	    		alert("请先选择需要编辑的行!");
	    		return false;
	    	} else {
	    		var params = {"eid" : selectedRowId};
	    		// 从Server读取对应ID的JSON数据
	    		$.ajax( {
	    			type:"POST",   
	    			url : getContextPath()+"/site/site/getSiteByID.do",
	    			data : params,
	    			dataType : "json",
	    			//contentType: "application/json",
	    			cache : false,
	    			async:false,
	    			error : function(textStatus, errorThrown) {
						alert("系统ajax交互错误: " + textStatus.responseText);
					},
					success : function(data, textStatus) {
						// 如果读取结果成功，则将信息载入到对话框中     
						var rowData = data;
						var consoleDlg = $("#consoleDlg");

						//consoleDlg.find("#selectId").val(rowData.id);
						//alert("hiddenID1:"+consoleDlg.find("#selectId").val());
						//row 1
						consoleDlg.find("#id").val(rowData.id);
						consoleDlg.find("#name").val(rowData.name);
						consoleDlg.find("#monitorType").val(rowData.monitorType.id);
						consoleDlg.find("#area").val(rowData.area.id);
						//row 2
						//valleyname, waterSystem, alongSide
						consoleDlg.find("#valleyname").val(rowData.valley.name).change();
						consoleDlg.find("#waterSystem").val(rowData.valley.waterSystem).change();
						consoleDlg.find("#alongSide").val(rowData.valley.alongSide);
						consoleDlg.find("#gprsID").val(rowData.gprsID);
						//row 3
						consoleDlg.find("#quality").val(rowData.qualityLevel);						
						consoleDlg.find("#contact").val(rowData.contact);
						consoleDlg.find("#telephone").val(rowData.telephone);
						consoleDlg.find("#mobile").val(rowData.mobile);
						//row 4
						consoleDlg.find("#eMail").val(rowData.eMail);
						consoleDlg.find("#ipAddress").val(rowData.ipAddress);
						consoleDlg.find("#port").val(rowData.port);
						consoleDlg.find("#freqMin").val(rowData.freqMin);
						//row 5
						consoleDlg.find("#gpsFixed").val(rowData.gpsFixed);
						consoleDlg.find("#gpsLongitude").val(rowData.fixtedLongitude);
						consoleDlg.find("#gpsLatitude").val(rowData.fixtedLatitude);
						//row 6
						consoleDlg.find("#remark").val(rowData.remark);
						consoleDlg.find("#longitudeSetoff").val(rowData.longitudeSetoff);
						consoleDlg.find("#latitudeSetoff").val(rowData.latitudeSetoff);
						
						// 根据新载入的数据将表格中的对应数据行一并更新一下
						var dataRow = {
								id : rowData.id, 
								name : rowData.name,
								"monitorType.name" : rowData.monitorType.name,
								"area.province" : rowData.area.province,
								"valley.name" : rowData.valley.name,
								"valley.watersystem" : rowData.valley.waterSystem,
								"valley.alongside" : rowData.valley.alongSide,
								qualityName : rowData.qualityName
						};

						$("#gridTable").jqGrid("setRowData", data.id, dataRow);

						// 打开对话框
						consoleDlg.dialog("open");
					}
	    		});
	    	}
		};
		
		var checkValid = function() {
	    	var consoleDlg = $("#consoleDlg");
	    	
	    	var id = $.trim(consoleDlg.find("#id").val()); 	
	    	if (id=="") {
	    		alert("'站点编号'为必填信息");
	    		return false;
	    	}
	    	var name = $.trim(consoleDlg.find("#name").val()); 	
	    	if (name=="") {
	    		alert("'站点名称'为必填信息");
	    		return false;
	    	}
	    	var MTypeID = $.trim(consoleDlg.find("#monitorType").val()); 
	    	if (MTypeID=="no") {
	    		alert("'监测类别'为必选信息");
	    		return false;
	    	}
			var itemID = $.trim(consoleDlg.find("#area").val());
			if (itemID=="no") {
	    		alert("'区域名称'为必选信息");
	    		return false;
	    	}		
			var valleyname = $.trim(consoleDlg.find("#valleyname").val());
			if (valleyname=="no") {
	    		alert("'流域'为必选信息");
	    		return false;
	    	}	
			var waterSystem = $.trim(consoleDlg.find("#waterSystem").val());
			if (waterSystem=="no") {
	    		alert("'水系'为必选信息");
	    		return false;
	    	}	
			var alongSide = $.trim(consoleDlg.find("#alongSide").val());
			if (alongSide=="no") {
	    		alert("'断面'为必选信息");
	    		return false;
	    	}	
			var qualityLevel = $.trim(consoleDlg.find("#quality").val());
			if (qualityLevel=="no") {
	    		alert("'评测标准'为必选信息");
	    		return false;
	    	}	
	    }
		
		var addInfo = function() {
			var consoleDlg = $("#consoleDlg");

			if (checkValid()==false) return false;
			
			//row 1
			var id = $.trim(consoleDlg.find("#id").val());
			var name = $.trim(consoleDlg.find("#name").val());
			var mTypeID = consoleDlg.find("#monitorType").val();
			var areaID = consoleDlg.find("#area").val();
			//row 2
			//valleyname, waterSystem, alongSide
			var valleyname = consoleDlg.find("#valleyname").val();
			var waterSystem = consoleDlg.find("#waterSystem").val();
			var alongSide = consoleDlg.find("#alongSide").val();
			var gprsID = $.trim(consoleDlg.find("#gprsID").val());
			//row 3
			var qualityName = $.trim(consoleDlg.find("#quality").find("option:selected").text());
			var qualityLevel = consoleDlg.find("#quality").val();
			//由于需要将qualitylevel转成int，而默认是'no'，因此将其转换成0
			if (qualityLevel=='no') {
				qualityLevel = 0;
			}
			var contact = $.trim(consoleDlg.find("#contact").val());
			var telephone = $.trim(consoleDlg.find("#telephone").val());
			var mobile = $.trim(consoleDlg.find("#mobile").val());
			//row 4
			var eMail = $.trim(consoleDlg.find("#eMail").val());
			var ipAddress = $.trim(consoleDlg.find("#ipAddress").val());
			var port = $.trim(consoleDlg.find("#port").val());
			var freqMin = $.trim(consoleDlg.find("#freqMin").val());
			if (freqMin=='') {
				freqMin = 0;
			}
			//row 5
			var gpsFixed = $.trim(consoleDlg.find("#gpsFixed").val());
			var gpsLongitude = $.trim(consoleDlg.find("#gpsLongitude").val());
			var gpsLatitude = $.trim(consoleDlg.find("#gpsLatitude").val());
			//row 6
			var remark = $.trim(consoleDlg.find("#remark").val());
			var longitudeSetoff = $.trim(consoleDlg.find("#longitudeSetoff").val());
			if (longitudeSetoff=='') {
				longitudeSetoff = 0;
			}
			var latitudeSetoff = $.trim(consoleDlg.find("#latitudeSetoff").val());
			if (latitudeSetoff=='') {
				latitudeSetoff = 0;
			}
			
			var valleyID = 0;
			for (var i=0; i<valleyInfos.length; i++) {
				if (valleyInfos[i].name==valleyname && valleyInfos[i].waterSystem==waterSystem && valleyInfos[i].alongSide==alongSide) {
					var valleyID = valleyInfos[i].id;
					break;
				}
			}
			
			var params = {
					"id" : id,
					"mTypeID" : mTypeID ,
					"areaID" : areaID,
					"name" : name,
					"gprsID" : gprsID,
					"valleyID" : valleyID,
					"qualityName" : qualityName,
					"qualityLevel" : qualityLevel,
					"contact" : contact,
					"telephone" : telephone,
					"mobile" : mobile,
					"eMail" : eMail,
					"ipAddress" : ipAddress,
					"port" : port,
					"freqMin" : freqMin,
					"gpsFixed" : gpsFixed,
					"gpsLongitude" : gpsLongitude,
					"gpsLatitude" : gpsLatitude,
					"remark" : remark,
					"longitudeSetoff": longitudeSetoff,
					"latitudeSetoff": latitudeSetoff
			};

			var actionUrl = getContextPath()+"/site/site/addSite.do";

			$.ajax( {
					type: "POST",
					url : actionUrl,
					data : params,
					dataType : "json",
					cache : false,
					error : function(textStatus, errorThrown) {
						alert("系统ajax交互错误: " + textStatus);
					},
					success : function(data, textStatus) {
						if (data != null) {
							var dataRow = {
									id : data.id, 
									name : data.name,
									"monitorType.name" : data.monitorType.name,
									"area.province" : data.area.province,
									"valley.name" : data.valley.name,
									"valley.waterSystem" : data.valley.waterSystem,
									"valley.alongSide" : data.valley.alongSide,
									qualityName : data.qualityName
							};

							var srcrowid = $("#gridTable").jqGrid("getGridParam",
									"selrow");

							if (srcrowid) {
								$("#gridTable").jqGrid("addRowData",
										data.id, dataRow, "before",
										srcrowid);

							} else {
								$("#gridTable").jqGrid("addRowData",
										data.id, dataRow, "first");
							}
							consoleDlg.dialog("close");

							alert("站点信息添加操作成功!");

						} else {
							alert("[站点名称]重复，添加操作失败!");
						}
					}
				});  
		};
		
		var updateInfo = function() {
			var consoleDlg = $("#consoleDlg");

			if (checkValid()==false) return false;
			
			//row 1
			var id = $.trim(consoleDlg.find("#id").val());
			var name = $.trim(consoleDlg.find("#name").val());
			var mTypeID = consoleDlg.find("#monitorType").val();
			var areaID = consoleDlg.find("#area").val();
			//row 2
			//valleyname, waterSystem, alongSide
			var valleyname = consoleDlg.find("#valleyname").val();
			var waterSystem = consoleDlg.find("#waterSystem").val();
			var alongSide = consoleDlg.find("#alongSide").val();
			var gprsID = $.trim(consoleDlg.find("#gprsID").val());
			//row 3
			var qualityName = $.trim(consoleDlg.find("#quality").find("option:selected").text());
			var qualityLevel = consoleDlg.find("#quality").val();
			var contact = $.trim(consoleDlg.find("#contact").val());
			var telephone = $.trim(consoleDlg.find("#telephone").val());
			var mobile = $.trim(consoleDlg.find("#mobile").val());
			//row 4
			var eMail = $.trim(consoleDlg.find("#eMail").val());
			var ipAddress = $.trim(consoleDlg.find("#ipAddress").val());
			var port = $.trim(consoleDlg.find("#port").val());
			var freqMin = $.trim(consoleDlg.find("#freqMin").val());
			if (freqMin=='') {
				freqMin = 0;
			}
			//row 5
			var gpsFixed = $.trim(consoleDlg.find("#gpsFixed").val());
			var gpsLongitude = $.trim(consoleDlg.find("#gpsLongitude").val());
			var gpsLatitude = $.trim(consoleDlg.find("#gpsLatitude").val());
			//row 6
			var remark = $.trim(consoleDlg.find("#remark").val());
			var longitudeSetoff = $.trim(consoleDlg.find("#longitudeSetoff").val());
			if (longitudeSetoff=='') {
				longitudeSetoff = 0;
			}
			var latitudeSetoff = $.trim(consoleDlg.find("#latitudeSetoff").val());
			if (latitudeSetoff=='') {
				latitudeSetoff = 0;
			}
			
			var valleyID = "";
			for (var i=0; i<valleyInfos.length; i++) {
				if (valleyInfos[i].name==valleyname && valleyInfos[i].waterSystem==waterSystem && valleyInfos[i].alongSide==alongSide) {
					var valleyID = valleyInfos[i].id;
					break;
				}
			}
			
			var params = {
					"id" : id,
					"mTypeID" : mTypeID ,
					"areaID" : areaID,
					"name" : name,
					"gprsID" : gprsID,
					"valleyID" : valleyID,
					"qualityName" : qualityName,
					"qualityLevel" : qualityLevel,
					"contact" : contact,
					"telephone" : telephone,
					"mobile" : mobile,
					"eMail" : eMail,
					"ipAddress" : ipAddress,
					"port" : port,
					"freqMin" : freqMin,
					"gpsFixed" : gpsFixed,
					"gpsLongitude" : gpsLongitude,
					"gpsLatitude" : gpsLatitude,
					"remark" : remark,
					"longitudeSetoff": longitudeSetoff,
					"latitudeSetoff": latitudeSetoff
			};
			var actionUrl = getContextPath()+"/site/site/updateSite.do";

			$.ajax( {
				type : "POST",
				url : actionUrl,
				data : params,
				dataType : "json",
				cache : false,
				error : function(textStatus, errorThrown) {
					alert("系统ajax交互错误: " + textStatus);
				},
				success : function(data, textStatus) {
					if (data != null) {
						var dataRow = {
								id : data.id, 
								name : data.name,
								"monitorType.name" : data.monitorType.name,
								"area.province" : data.area.province,
								"valley.name" : data.valley.name,
								"valley.waterSystem" : data.valley.waterSystem,
								"valley.alongSide" : data.valley.alongSide,
								qualityName : data.qualityName
						};
						alert("站点信息更新成功!");
						consoleDlg.dialog("close");
						$("#gridTable").jqGrid("setRowData", data.id, dataRow);
					} else {
						alert("[站点名称]重复，修改操作失败!");
					}
				}
			});
		};
		
		var deleteInfo = function() {
			var consoleDlg = $("#consoleDlg");  
			
			var r=confirm("确认要删除该信息吗？");
			if (r==false) {
				consoleDlg.dialog("close"); 
				return false;
			}
	        
			var pId = $.trim(consoleDlg.find("#id").val());
	        var params = {"eID" : pId};  
	        var actionUrl = getContextPath() + "/site/site/deleteSite.do";
	        $.ajax({  
	        	type : "POST",
	            url : actionUrl,  
	            data : params,  
	            //dataType : "json",  
	            cache : false,  
	            error : function(textStatus, errorThrown) {  
	                alert("系统ajax交互错误: " + textStatus);  
	            },  
	            success : function(data, textStatus) {  
	                if (data == "success") {  
	                    $("#gridTable").jqGrid("delRowData", pId);  
	                    consoleDlg.dialog("close");  
	                    alert("站点信息删除成功!");  
	                } else {  
	                    alert("删除操作失败!");  
	                }  
	            }  
	        });  
		};